package com.xydzxt.www.controller.student;

import com.xydzxt.www.model.Examinee;
import com.xydzxt.www.model.Pay;
import com.xydzxt.www.model.Regist;
import com.xydzxt.www.service.ExamineeService;
import com.xydzxt.www.service.PayService;
import com.xydzxt.www.service.RegistService;
import com.xydzxt.www.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

@Controller
public class PayController {
    @Autowired
    RegistService registService;
    @Autowired
    PayService payService;
    @Autowired
    ExamineeService examineeService;

    @PostMapping("/pay")
    public void payPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        HttpSession session=req.getSession();
        String idNumber=session.getAttribute("sfzh").toString();
        Regist regist=registService.selectByIdNumber(idNumber);
        Pay isPay=payService.selectBuRegistId(regist.getRegistId());

        if (isPay==null){
            Pay pay=new Pay();
            pay.setRegistId(regist.getRegistId());
            pay.setPayType(1);
            pay.setPrice(120);
            pay.setInputName(idNumber);
            pay.setInputDate(new DateUtil().getStringDate("yyyy-MM-dd HH:mm:ss"));
            boolean isSuccess=payService.insert(pay);
            if (isSuccess){
                Examinee examinee=new Examinee();
                examinee.setRegistId(regist.getRegistId());
                String zkzh="20"+new DateUtil().getStringDate("ddHHmmss")+(new Random().nextInt(900)+100);
                examinee.setExamineeId(zkzh);

                examinee.setAcceptStatus(1);
                examinee.setInputName(idNumber);
                examinee.setInputDate(new DateUtil().getStringDate("yyyy-MM-dd HH:mm:ss"));

                examineeService.insert(examinee);
                resp.getWriter().write("true");
            }else {
                resp.getWriter().write("false");
            }
        }else {
            resp.getWriter().write("false");
        }

    }

    @GetMapping("/pay")
    public String payGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session=req.getSession();
        if (session.getAttribute("sfzh")!=null){
            return "student/weChatPayment";
        }else{
            resp.sendRedirect("index");
        }
        return "";
    }
}
